<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>国际跳棋 (64格) v1.04</title>
<!--  国际跳棋 (64格) 2025.8 v1.04 夏勇（笔名：银河）,通义灵码辅助生成 -->
    <style>
        :root {
            --board-square-size-large: 60px;
            --board-square-size-medium: 50px;
            --board-square-size-small: 40px;
            --board-square-size-xsmall: 35px;
            --board-square-size-xxsmall: 30px;
            
            /* 新增配色变量 */
            --primary-color: #3498db;
            --primary-dark: #2980b9;
            --secondary-color: #2c3e50;
            --accent-color: #e74c3c;
            --light-bg: #f8f9fa;
            --dark-bg: #ecf0f1;
            --text-dark: #2c3e50;
            --text-light: #ffffff;
            --border-color: #bdc3c7;
            --success-color: #27ae60;
            --success-dark: #219653;
        }

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            display: flex;
            flex-direction: column;
            align-items: center;
            background: linear-gradient(135deg, #f5f7fa 0%, #e4edf5 100%);
            margin: 0;
            padding: 10px;
            min-height: 100vh;
        }

        h1 {
            color: var(--secondary-color);
            text-align: center;
            margin: 10px 0;
            font-size: 1.8rem;
            text-shadow: 1px 1px 2px rgba(0,0,0,0.1);
        }

        .game-container {
            display: flex;
            flex-wrap: wrap;
            justify-content: center;
            gap: 20px;
            width: 100%;
            max-width: 1200px;
        }

        .board-container {
            position: relative;
            display: flex;
            flex-direction: column;
            align-items: center;
        }

        .status {
            margin-bottom: 15px;
            font-size: 1.2em;
            font-weight: bold;
            height: 1.5em;
            text-align: center;
            color: var(--secondary-color);
            background-color: rgba(255, 255, 255, 0.8);
            padding: 8px 20px;
            border-radius: 20px;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
        }

        .controls {
            display: flex;
            flex-direction: column;
            gap: 10px;
            min-width: 150px;
        }

        button {
            padding: 12px 15px;
            font-size: 1em;
            cursor: pointer;
            border: none;
            border-radius: 6px;
            background-color: var(--primary-color);
            color: var(--text-light);
            transition: all 0.3s ease;
            min-width: 120px;
            font-weight: 600;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
        }

        button:hover {
            background-color: var(--primary-dark);
            transform: translateY(-2px);
            box-shadow: 0 4px 8px rgba(0,0,0,0.15);
        }

        button:disabled {
            background-color: #bdc3c7;
            cursor: not-allowed;
            transform: none;
            box-shadow: none;
        }

        .mode-selector {
            margin-bottom: 15px;
        }

        .mode-selector label {
            display: block;
            margin-bottom: 8px;
            color: var(--text-dark);
            font-weight: 500;
        }

        /* Tabs 样式优化 */
        .tabs-container {
            width: 100%;
            max-width: 500px;
            margin-top: 20px;
            border-radius: 8px;
            overflow: hidden;
            box-shadow: 0 4px 15px rgba(0,0,0,0.1);
            display: flex;
            flex-direction: column;
            height: 100%;
        }

        .tab-buttons {
            display: flex;
            background-color: var(--secondary-color);
            margin-bottom: 0;
        }

        .tab-button {
            padding: 16px 20px;
            cursor: pointer;
            background-color: rgba(44, 62, 80, 0.8);
            border: none;
            color: var(--text-light);
            font-weight: 600;
            transition: all 0.3s ease;
            flex: 1;
            text-align: center;
            font-size: 1rem;
            position: relative;
        }

        .tab-button:hover {
            background-color: rgba(52, 152, 219, 0.9);
        }

        .tab-button.active {
            background-color: var(--primary-color);
            color: var(--text-light);
        }

        .tab-button.active::after {
            content: '';
            position: absolute;
            bottom: 0;
            left: 0;
            width: 100%;
            height: 4px;
            background-color: var(--accent-color);
        }

        .tab-content-container {
            flex: 1;
            display: flex;
            flex-direction: column;
            min-height: 0; /* 允许容器收缩 */
        }

        .tab-content {
            display: none;
            padding: 25px;
            background-color: var(--light-bg);
            flex: 1;
            overflow-y: auto;
            border-top: none;
            animation: fadeIn 0.4s ease;
            min-height: 280px;
        }

        .tab-content.active {
            display: flex;
            flex-direction: column;
        }

        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(10px); }
            to { opacity: 1; transform: translateY(0); }
        }

        /* 控制面板样式 */
        .control-panel {
            display: flex;
            flex-direction: column;
            gap: 18px;
            flex: 1;
        }

        /* 行棋记录样式 */
        #historyList {
            list-style-type: none;
            padding: 0;
            margin: 0;
            flex: 1;
            overflow-y: auto;
        }

        #historyList li {
            padding: 12px 15px;
            border-bottom: 1px solid var(--border-color);
            font-family: 'Courier New', monospace;
            font-size: 1.1em;
            transition: background-color 0.2s;
            border-radius: 4px;
            margin-bottom: 5px;
        }

        #historyList li:hover {
            background-color: var(--dark-bg);
        }

        #historyList li:last-child {
            border-bottom: none;
            margin-bottom: 0;
        }

        #historyList li:nth-child(odd) {
            background-color: var(--dark-bg);
        }

        /* 规则内容样式 */
        .rules-content {
            line-height: 1.7;
            color: var(--text-dark);
            flex: 1;
            overflow-y: auto;
        }

        .rules-content h3 {
            color: var(--secondary-color);
            margin-top: 0;
            border-bottom: 3px solid var(--primary-color);
            padding-bottom: 10px;
            margin-bottom: 20px;
            font-size: 1.5rem;
        }

        .rules-content h4 {
            color: var(--primary-dark);
            margin-top: 25px;
            margin-bottom: 12px;
            font-size: 1.2rem;
            border-left: 4px solid var(--primary-color);
            padding-left: 12px;
        }

        .rules-content ul {
            padding-left: 25px;
        }

        .rules-content li {
            margin-bottom: 12px;
            padding-left: 10px;
        }

        .rules-content li strong {
            color: var(--primary-dark);
        }

        .highlight {
            background-color: #ffff99 !important;
        }

        /* 棋盘和棋子样式 */
        .board {
            display: grid;
            grid-template-columns: repeat(8, var(--board-square-size-large));
            grid-template-rows: repeat(8, var(--board-square-size-large));
            border: 3px solid var(--secondary-color);
            box-shadow: 0 0 20px rgba(0,0,0,0.25);
            border-radius: 6px;
        }

        .square {
            width: var(--board-square-size-large);
            height: var(--board-square-size-large);
            display: flex;
            justify-content: center;
            align-items: center;
            font-size: calc(var(--board-square-size-large) * 0.66);
            cursor: pointer;
            user-select: none;
        }

        .light {
            background-color: #F0D9B5; /* 浅色格子 */
        }

        .dark {
            background-color: #B58863; /* 深色格子 */
        }

        .piece {
            width: calc(var(--board-square-size-large) * 0.75);
            height: calc(var(--board-square-size-large) * 0.75);
            border-radius: 50%;
            display: flex;
            justify-content: center;
            align-items: center;
            font-weight: bold;
            box-shadow: 0 3px 6px rgba(0,0,0,0.2);
            transition: transform 0.2s ease, box-shadow 0.2s ease;
            z-index: 10;
        }

        .piece:hover {
            transform: scale(1.08);
            box-shadow: 0 5px 12px rgba(0,0,0,0.3);
        }

        .black {
            background: linear-gradient(145deg, #444, #000);
            color: white;
            border: 2px solid #000;
        }

        .white {
            background: linear-gradient(145deg, #fff, #ddd);
            color: #333;
            border: 2px solid #aaa;
        }

        .king::after {
            content: "♔";
            font-size: calc(var(--board-square-size-large) * 0.4);
        }

        .selected {
            box-shadow: 0 0 0 4px #27ae60 inset !important;
            animation: pulse 1.5s infinite;
        }

        @keyframes pulse {
            0% { box-shadow: 0 0 0 0 rgba(39, 174, 96, 0.7); }
            70% { box-shadow: 0 0 0 10px rgba(39, 174, 96, 0); }
            100% { box-shadow: 0 0 0 0 rgba(39, 174, 96, 0); }
        }

        .valid-move {
            position: relative;
        }

        .valid-move::before {
            content: "";
            position: absolute;
            width: calc(var(--board-square-size-large) * 0.33);
            height: calc(var(--board-square-size-large) * 0.33);
            background-color: rgba(39, 174, 96, 0.7);
            border-radius: 50%;
            z-index: 5;
            animation: pulse-dot 1.5s infinite;
        }

        @keyframes pulse-dot {
            0% { transform: scale(0.8); opacity: 0.9; }
            50% { transform: scale(1.1); opacity: 1; }
            100% { transform: scale(0.8); opacity: 0.9; }
        }

        /* 响应式优化 */
        @media (max-width: 1200px) {
            .game-container {
                max-width: 900px;
            }
        }

        @media (max-width: 992px) {
            :root {
                --board-square-size-large: 55px;
            }
            
            .game-container {
                max-width: 750px;
            }
            
            h1 {
                font-size: 1.6rem;
            }
        }

        @media (max-width: 768px) {
            :root {
                --board-square-size-large: 50px;
            }
            
            .game-container {
                flex-direction: column;
                align-items: center;
                max-width: 100%;
            }
            
            .controls {
                flex-direction: row;
                flex-wrap: wrap;
                justify-content: center;
                min-width: unset;
                width: 100%;
                max-width: 350px;
                margin-top: 20px;
            }
            
            .mode-selector {
                width: 100%;
                text-align: center;
            }
            
            .board {
                grid-template-columns: repeat(8, var(--board-square-size-large));
                grid-template-rows: repeat(8, var(--board-square-size-large));
            }
            
            .square {
                width: var(--board-square-size-large);
                height: var(--board-square-size-large);
                font-size: calc(var(--board-square-size-large) * 0.66);
            }
            
            .piece {
                width: calc(var(--board-square-size-large) * 0.75);
                height: calc(var(--board-square-size-large) * 0.75);
            }
            
            .king::after {
                font-size: calc(var(--board-square-size-large) * 0.4);
            }
            
            .valid-move::before {
                width: calc(var(--board-square-size-large) * 0.33);
                height: calc(var(--board-square-size-large) * 0.33);
            }
            
            .tabs-container {
                max-width: 100%;
            }
            
            h1 {
                font-size: 1.5rem;
            }
        }

        @media (max-width: 576px) {
            :root {
                --board-square-size-large: 45px;
            }
            
            body {
                padding: 5px;
            }
            
            .game-container {
                gap: 15px;
            }
            
            .controls {
                max-width: 100%;
            }
            
            button {
                padding: 10px 12px;
                font-size: 0.9em;
                min-width: 100px;
            }
            
            h1 {
                font-size: 1.4rem;
                margin: 5px 0;
            }
            
            .status {
                font-size: 1.1em;
                margin-bottom: 10px;
                padding: 6px 15px;
            }
            
            .tab-buttons {
                flex-wrap: wrap;
            }
            
            .tab-button {
                font-size: 0.9em;
                padding: 14px 10px;
            }
            
            .tab-content {
                padding: 15px;
            }
        }

        @media (max-width: 480px) {
            :root {
                --board-square-size-large: 40px;
            }
            
            .board {
                grid-template-columns: repeat(8, var(--board-square-size-large));
                grid-template-rows: repeat(8, var(--board-square-size-large));
            }
            
            .square {
                width: var(--board-square-size-large);
                height: var(--board-square-size-large);
                font-size: calc(var(--board-square-size-large) * 0.66);
            }
            
            .piece {
                width: calc(var(--board-square-size-large) * 0.75);
                height: calc(var(--board-square-size-large) * 0.75);
            }
            
            .king::after {
                font-size: calc(var(--board-square-size-large) * 0.4);
            }
            
            .valid-move::before {
                width: calc(var(--board-square-size-large) * 0.33);
                height: calc(var(--board-square-size-large) * 0.33);
            }
            
            h1 {
                font-size: 1.3rem;
            }
        }

        @media (max-width: 400px) {
            :root {
                --board-square-size-large: 35px;
            }
            
            .board {
                grid-template-columns: repeat(8, var(--board-square-size-large));
                grid-template-rows: repeat(8, var(--board-square-size-large));
            }
            
            .square {
                width: var(--board-square-size-large);
                height: var(--board-square-size-large);
                font-size: calc(var(--board-square-size-large) * 0.66);
            }
            
            .piece {
                width: calc(var(--board-square-size-large) * 0.75);
                height: calc(var(--board-square-size-large) * 0.75);
            }
            
            .king::after {
                font-size: calc(var(--board-square-size-large) * 0.4);
            }
            
            .valid-move::before {
                width: calc(var(--board-square-size-large) * 0.33);
                height: calc(var(--board-square-size-large) * 0.33);
            }
            
            button {
                padding: 8px 10px;
                font-size: 0.85em;
                min-width: 90px;
            }
            
            h1 {
                font-size: 1.2rem;
            }
        }

        /* 超大屏幕优化 */
        @media (min-width: 1400px) {
            :root {
                --board-square-size-large: 70px;
            }
            
            .game-container {
                max-width: 1400px;
            }
            
            .board {
                grid-template-columns: repeat(8, var(--board-square-size-large));
                grid-template-rows: repeat(8, var(--board-square-size-large));
            }
            
            .square {
                width: var(--board-square-size-large);
                height: var(--board-square-size-large);
                font-size: calc(var(--board-square-size-large) * 0.66);
            }
            
            .piece {
                width: calc(var(--board-square-size-large) * 0.75);
                height: calc(var(--board-square-size-large) * 0.75);
            }
            
            .king::after {
                font-size: calc(var(--board-square-size-large) * 0.4);
            }
            
            .valid-move::before {
                width: calc(var(--board-square-size-large) * 0.33);
                height: calc(var(--board-square-size-large) * 0.33);
            }
        }

        @media (min-width: 1800px) {
            :root {
                --board-square-size-large: 80px;
            }
            
            .board {
                grid-template-columns: repeat(8, var(--board-square-size-large));
                grid-template-rows: repeat(8, var(--board-square-size-large));
            }
            
            .square {
                width: var(--board-square-size-large);
                height: var(--board-square-size-large);
                font-size: calc(var(--board-square-size-large) * 0.66);
            }
            
            .piece {
                width: calc(var(--board-square-size-large) * 0.75);
                height: calc(var(--board-square-size-large) * 0.75);
            }
            
            .king::after {
                font-size: calc(var(--board-square-size-large) * 0.4);
            }
            
            .valid-move::before {
                width: calc(var(--board-square-size-large) * 0.33);
                height: calc(var(--board-square-size-large) * 0.33);
            }
        }
        
        /* 横屏优化：当屏幕宽度大于高度时 */
        @media (orientation: landscape) and (min-width: 1024px) {
            .game-container {
                flex-direction: row;
                align-items: flex-start;
                justify-content: center;
                max-width: 100%;
                gap: 20px;
            }
            
            .board-container {
                margin-right: 20px;
            }
            
            .tabs-container {
                width: 350px;
                margin-top: 70px;
                align-self: flex-start;
                flex-shrink: 0;
            }
            
            .tab-content {
                min-height: 300px;
            }
        }
        
        @media (orientation: landscape) and (min-width: 1400px) {
            .tabs-container {
                width: 400px;
            }
        }
        
        @media (orientation: landscape) and (min-width: 1800px) {
            .tabs-container {
                width: 450px;
            }
        }
    </style>
    <style>
        footer {
            text-align: center;
            color: #7f8c8d;
            font-size: 0.875rem;
            margin-top: 2rem;
            width: 100%;
            padding: 1rem 0;
        }
    </style>
</head>
<body>

<h1>国际跳棋 (64格)</h1>

<div class="game-container">
    <div class="board-container">
        <div class="status" id="status">黑方先行</div>
        <div class="board" id="checkerboard"></div>
    </div>

    <div class="tabs-container">
        <div class="tab-buttons">
            <button class="tab-button active" data-tab="controls">游戏控制</button>
            <button class="tab-button" data-tab="history">行棋记录</button>
            <button class="tab-button" data-tab="rules">游戏规则</button>
        </div>

        <div class="tab-content-container">
            <div id="controls" class="tab-content active">
                <div class="control-panel">
                    <div class="mode-selector">
                        <label>
                            <input type="radio" name="mode" value="pvp" checked> 双人对战
                        </label>
                        <label>
                            <input type="radio" name="mode" value="pvc"> 人机对战
                        </label>
                    </div>
                    <button id="newGameBtn">新游戏</button>
                    <button id="undoBtn" disabled>悔棋</button>
                    <button id="passBtn" style="display:none;">跳过回合</button>
                </div>
            </div>

            <div id="history" class="tab-content">
                <ul id="historyList"></ul>
            </div>

            <div id="rules" class="tab-content">
                <div class="rules-content">
                    <h3>国际跳棋规则</h3>
                    
                    <h4>棋盘与棋子</h4>
                    <ul>
                        <li>棋盘为8×8的黑白相间方格，只有深色格子可以放置棋子</li>
                        <li>双方各有12枚棋子，黑方先行</li>
                        <li>初始位置：黑子在第1-3行，白子在第6-8行的深色格子上</li>
                    </ul>
                    
                    <h4>棋子移动</h4>
                    <ul>
                        <li><strong>普通棋子</strong>：只能向前斜向移动一格到相邻的空格</li>
                        <li><strong>王棋</strong>：可向前或向后斜向移动任意格数</li>
                        <li>移动时不能跳过己方棋子</li>
                    </ul>
                    
                    <h4>吃子规则</h4>
                    <ul>
                        <li>当对方棋子在相邻格时，如果其后方紧邻的格子为空，可以跳过对方棋子吃掉它</li>
                        <li>一次跳跃可连续进行，只要条件满足，必须完成所有可能的跳跃</li>
                        <li><strong>强制吃子</strong>：如果有吃子机会，必须选择吃子，且必须选择能吃掉最多棋子的路径</li>
                    </ul>
                    
                    <h4>晋升规则</h4>
                    <ul>
                        <li>普通棋子移动到对方底线（最远端）时，立即升为王棋</li>
                        <li>王棋有特殊标识（带王冠 ♔）且可向任意方向移动和跳跃</li>
                    </ul>
                    
                    <h4>胜负判定</h4>
                    <ul>
                        <li>吃掉对方所有棋子获胜</li>
                        <li>使对方无法移动任何棋子获胜</li>
                    </ul>
                </div>
            </div>
        </div>
    </div>
</div>
<div>
    <!-- 页脚 -->
    <footer>
        <p>国际跳棋 &copy; 2025 银河 </p>
    </footer>   
</div>   

<script>
    // --- 游戏状态和常量 ---
    const BOARD_SIZE = 8;
    const EMPTY = 0;
    const BLACK_PIECE = 1; // 普通黑子
    const WHITE_PIECE = 2; // 普通白子
    const BLACK_KING = 3;  // 黑王
    const WHITE_KING = 4;  // 白王

    let board = [];
    let currentPlayer = BLACK_PIECE; // 黑方先手
    let selectedPiece = null; // {row, col}
    let validMoves = []; // 当前选中棋子的有效移动
    let moveHistory = []; // 存储完整回合的移动历史
    let gameMode = 'pvp'; // 'pvp' 或 'pvc'
    let isGameOver = false;
    let isProcessingMove = false; // 防止在处理移动时点击
    let currentMoveSequence = []; // 用于记录当前连续跳跃的序列

    // --- DOM 元素 ---
    const boardElement = document.getElementById('checkerboard');
    const statusElement = document.getElementById('status');
    const newGameBtn = document.getElementById('newGameBtn');
    const undoBtn = document.getElementById('undoBtn');
    const passBtn = document.getElementById('passBtn');
    const modeRadios = document.querySelectorAll('input[name="mode"]');
    const historyList = document.getElementById('historyList');
    const tabButtons = document.querySelectorAll('.tab-button');
    const tabContents = document.querySelectorAll('.tab-content');

    // --- 初始化 ---
    function initGame() {
        createBoard();
        resetGame();
        setupEventListeners();
        setupTabs();
    }

    function setupTabs() {
        tabButtons.forEach(button => {
            button.addEventListener('click', () => {
                const tabId = button.getAttribute('data-tab');
                
                // 更新激活的按钮
                tabButtons.forEach(btn => btn.classList.remove('active'));
                button.classList.add('active');
                
                // 显示对应的内容面板
                tabContents.forEach(content => {
                    content.classList.remove('active');
                    if (content.id === tabId) {
                        content.classList.add('active');
                    }
                });
            });
        });
    }

    function createBoard() {
        boardElement.innerHTML = '';
        for (let row = 0; row < BOARD_SIZE; row++) {
            for (let col = 0; col < BOARD_SIZE; col++) {
                const square = document.createElement('div');
                square.classList.add('square');
                square.classList.add((row + col) % 2 === 0 ? 'light' : 'dark');
                square.dataset.row = row;
                square.dataset.col = col;
                boardElement.appendChild(square);
            }
        }
    }

    function resetGame() {
        board = Array(BOARD_SIZE).fill().map(() => Array(BOARD_SIZE).fill(EMPTY));
        currentPlayer = BLACK_PIECE;
        selectedPiece = null;
        validMoves = [];
        moveHistory = [];
        currentMoveSequence = [];
        isGameOver = false;
        isProcessingMove = false;
        historyList.innerHTML = '';
        updateStatus();
        undoBtn.disabled = true;
        passBtn.style.display = 'none';

        // 清除之前的高亮（新增）
        clearHighlights();

        // 放置初始棋子
        for (let row = 0; row < BOARD_SIZE; row++) {
            for (let col = 0; col < BOARD_SIZE; col++) {
                if ((row + col) % 2 !== 0) { // 只在深色格子上放棋子
                    if (row < 3) {
                        board[row][col] = BLACK_PIECE;
                    } else if (row > 4) {
                        board[row][col] = WHITE_PIECE;
                    }
                }
            }
        }
        renderBoard();
        
        // 如果是人机模式且AI是先手（白方），则触发AI移动
        if (gameMode === 'pvc' && currentPlayer === WHITE_PIECE) {
            setTimeout(makeAIMove, 500); // 稍微延迟，让用户看到状态变化
        }
    }

    function setupEventListeners() {
        boardElement.addEventListener('click', handleSquareClick);
        newGameBtn.addEventListener('click', resetGame);
        undoBtn.addEventListener('click', undoMove);
        modeRadios.forEach(radio => {
            radio.addEventListener('change', () => {
                gameMode = radio.value;
                resetGame();
            });
        });
    }

    // --- 游戏逻辑 ---

    function handleSquareClick(event) {
        if (isGameOver || isProcessingMove) return;
        if (gameMode === 'pvc' && currentPlayer === WHITE_PIECE) return; // 人机模式下，玩家不能操作白方

        // 修复：确保点击的是格子本身，而不是其子元素（如棋子）
        const squareElement = event.target.closest('.square');
        if (!squareElement) return; // 如果点击的不是格子或其内部，直接返回

        const row = parseInt(squareElement.dataset.row, 10);
        const col = parseInt(squareElement.dataset.col, 10);

        // 确保 row 和 col 是有效数字
        if (isNaN(row) || isNaN(col)) {
            console.error("Invalid row or col data attributes:", squareElement.dataset);
            return;
        }

        // 点击的是棋子
        if (board[row][col] === currentPlayer || board[row][col] === (currentPlayer === BLACK_PIECE ? BLACK_KING : WHITE_KING)) {
            selectPiece(row, col);
        }
        // 点击的是有效移动目标格
        else if (selectedPiece && validMoves.some(move => move.toRow === row && move.toCol === col)) {
            // --- 修复：强制吃子规则检查 ---
            if (!isValidMoveAccordingToForcedCapture(row, col)) {
                statusElement.textContent = "必须选择吃子最多的路径！";
                setTimeout(updateStatus, 1500); // 1.5秒后恢复状态
                return; // 阻止非法移动
            }
            // --- 结束修复 ---
            
            const move = validMoves.find(m => m.toRow === row && m.toCol === col);
            initiateMove(selectedPiece.row, selectedPiece.col, move.toRow, move.toCol, move.capturedPieces);
        }
    }

    // --- 修复：检查移动是否符合强制吃子规则 ---
    // 关键修正：在获取所有棋子的潜在移动时，使用棋盘上实际的棋子类型 board[r][c]
    function isValidMoveAccordingToForcedCapture(targetRow, targetCol) {
        // 1. 获取当前玩家所有棋子的强制吃子移动
        let allForcedMoves = [];
        for (let r = 0; r < BOARD_SIZE; r++) {
            for (let c = 0; c < BOARD_SIZE; c++) {
                const piece = board[r][c];
                if (piece === currentPlayer || piece === (currentPlayer === BLACK_PIECE ? BLACK_KING : WHITE_KING)) {
                    // --- 关键修正：传入实际棋子类型 piece ---
                    const moves = getValidMoves(r, c, piece);
                    // 如果该棋子有吃子移动，则添加到强制移动列表
                    if (moves.length > 0 && moves.some(m => m.capturedPieces.length > 0)) {
                        // 为每个移动添加起点信息，方便后续比较
                        moves.forEach(m => { m.fromRow = r; m.fromCol = c; }); // 修复语法错误
                        allForcedMoves.push(...moves);
                    }
                }
            }
        }

        // 2. 如果存在强制吃子移动
        if (allForcedMoves.length > 0) {
            // a. 找到最大吃子数
            const maxCaptures = Math.max(...allForcedMoves.map(m => m.capturedPieces.length));
            
            // b. 筛选出吃子数最多的移动
            const bestForcedMoves = allForcedMoves.filter(m => m.capturedPieces.length === maxCaptures);

            // c. 检查玩家选择的移动（目标格和吃子数）是否符合最佳强制移动
            //    修复：不再要求起点必须是 selectedPiece
            const isMoveValid = bestForcedMoves.some(move => 
                move.toRow === targetRow && 
                move.toCol === targetCol && 
                move.capturedPieces.length === maxCaptures
            );

            return isMoveValid;
        }

        // 3. 如果没有强制吃子，则任何有效移动都允许
        return true;
    }
    // --- 结束修复 ---


    // --- 修复：强制吃子高亮逻辑 ---
    // 关键修正：在获取所有棋子的潜在移动和当前选中棋子的移动时，使用棋盘上实际的棋子类型
    function selectPiece(row, col) {
        // 清除之前的高亮
        clearHighlights();

        selectedPiece = { row, col };
        // --- 关键修正：传入实际棋子类型 board[row][col] ---
        validMoves = getValidMoves(row, col, board[row][col]);

        let allForcedMoves = [];
        let forcedPieces = [];
        for (let r = 0; r < BOARD_SIZE; r++) {
            for (let c = 0; c < BOARD_SIZE; c++) {
                const piece = board[r][c];
                if (piece === currentPlayer || piece === (currentPlayer === BLACK_PIECE ? BLACK_KING : WHITE_KING)) {
                    // --- 关键修正：传入实际棋子类型 piece ---
                    const moves = getValidMoves(r, c, piece);
                    if (moves.length > 0 && moves.some(m => m.capturedPieces.length > 0)) {
                        // 为每个移动添加起点信息，方便后续比较
                        moves.forEach(m => { m.fromRow = r; m.fromCol = c; }); // 修复语法错误
                        allForcedMoves.push(...moves);
                        forcedPieces.push({row: r, col: c});
                    }
                }
            }
        }

        if (allForcedMoves.length > 0) {
            const maxCaptures = Math.max(...allForcedMoves.map(m => m.capturedPieces.length));
            const bestForcedMoves = allForcedMoves.filter(m => m.capturedPieces.length === maxCaptures);
            
            // 高亮所有必须移动的棋子
            forcedPieces.forEach(p => highlightSquare(p.row, p.col, 'selected'));
            
            // 如果点击的棋子是必须移动的棋子之一，则高亮其最佳路径
            if (forcedPieces.some(p => p.row === row && p.col === col)) {
                 bestForcedMoves
                    .filter(move => move.fromRow === row && move.fromCol === col) // 筛选当前棋子的移动
                    .forEach(move => highlightSquare(move.toRow, move.toCol, 'valid-move'));
                 
                 // 更新 validMoves 为当前棋子的最佳移动
                 validMoves = bestForcedMoves.filter(move => move.fromRow === row && move.fromCol === col);
            } else {
                // 点击的不是必须移动的棋子，不显示任何移动高亮
                validMoves = []; // 清空有效移动，防止误操作
            }
        } else {
            // 没有强制吃子，按原逻辑高亮
            highlightSquare(row, col, 'selected');
            validMoves.forEach(move => {
                highlightSquare(move.toRow, move.toCol, 'valid-move');
            });
        }
    }
    // --- 结束修复 ---


    function clearHighlights() {
        document.querySelectorAll('.selected, .valid-move').forEach(el => {
            el.classList.remove('selected', 'valid-move');
        });
    }

    function highlightSquare(row, col, className) {
        const square = document.querySelector(`.square[data-row="${row}"][data-col="${col}"]`);
        if (square) {
            square.classList.add(className);
        }
    }

    // 获取有效移动，包括修正后的王棋规则和向后跳吃
    // --- 修正：新增 pieceType 参数，用于准确判断当前棋子的移动能力 ---
    function getValidMoves(fromRow, fromCol, pieceType) {
        // --- 修复错误：使用 fromCol 而不是未定义的 col ---
        const piece = pieceType; // 使用传入的棋子类型
        if (piece === EMPTY) return [];

        // --- 修正：根据传入的 pieceType 判断是否为王棋 ---
        const isKing = (piece === BLACK_KING || piece === WHITE_KING);
        const isBlack = (piece === BLACK_PIECE || piece === BLACK_KING);
        
        // 方向向量：[上左, 上右, 下左, 下右]
        const directions = [[-1, -1], [-1, 1], [1, -1], [1, 1]];

        let moves = [];
        let mustJump = false;
        let jumpMoves = [];

        // 1. 检查是否有吃子机会 (必须执行)
        for (const [dr, dc] of directions) {
            let r = fromRow + dr;
            let c = fromCol + dc;
            
            // 对于普通棋子，检查一步；对于王棋，检查多步
            while (r >= 0 && r < BOARD_SIZE && c >= 0 && c < BOARD_SIZE) {
                const targetPiece = board[r][c];
                
                if (targetPiece !== EMPTY) {
                    // 遇到自己的棋子，停止搜索这个方向
                    if ((isBlack && (targetPiece === BLACK_PIECE || targetPiece === BLACK_KING)) ||
                        (!isBlack && (targetPiece === WHITE_PIECE || targetPiece === WHITE_KING))) {
                        break;
                    }
                    // 遇到对方棋子，检查是否可以跳过
                    else {
                        // --- 更新：王棋吃子后可停任意空格 ---
                        // 找到对方棋子后，沿着同一方向继续寻找空格
                        let jumpR = r + dr;
                        let jumpC = c + dc;
                        while (jumpR >= 0 && jumpR < BOARD_SIZE && jumpC >= 0 && jumpC < BOARD_SIZE && board[jumpR][jumpC] === EMPTY) {
                            // 找到一个跳跃吃子的可能终点
                            mustJump = true;
                            const capturedPieces = [{ row: r, col: c, type: targetPiece }]; // 记录被吃子的类型
                            
                            // --- 修正：调用 findFurtherJumps 时传入 isKing 状态 ---
                            const furtherJumps = findFurtherJumps(jumpR, jumpC, [...capturedPieces], isKing, isBlack);
                            
                            if (furtherJumps.length > 0) {
                                // 添加所有找到的连跳路径
                                jumpMoves.push(...furtherJumps);
                            } else {
                                // 否则，这是一个终点
                                jumpMoves.push({ toRow: jumpR, toCol: jumpC, capturedPieces });
                            }
                            
                            // 王棋可以停在任意空格，所以继续寻找
                            if (isKing) {
                                jumpR += dr;
                                jumpC += dc;
                            } else {
                                // 普通棋子只能停在第一个空格
                                break;
                            }
                        }
                        break; // 在这个方向上找到一个跳跃（或检查完所有可能终点）后就停止搜索这个方向
                    }
                }
                
                // 如果是普通棋子，只能检查一步；王棋可以继续沿直线搜索
                if (!isKing) break;
                r += dr;
                c += dc;
            }
        }

        if (mustJump) {
            // 如果有跳跃，必须选择跳跃。返回所有最长的跳跃路径。
            if (jumpMoves.length > 0) {
                 const maxCaptures = Math.max(...jumpMoves.map(j => j.capturedPieces.length));
                 return jumpMoves.filter(j => j.capturedPieces.length === maxCaptures);
            }
            return jumpMoves; // fallback
        }

        // 2. 如果没有必须的跳跃，则检查普通移动
        // 普通棋子只能向前移动，王棋可以向四个方向移动
        const moveDirections = isKing ? directions : (isBlack ? [[1, -1], [1, 1]] : [[-1, -1], [-1, 1]]);

        for (const [dr, dc] of moveDirections) {
            let r = fromRow + dr;
            let c = fromCol + dc;
            
            // 普通棋子移动一步，王棋可以移动多步
            while (r >= 0 && r < BOARD_SIZE && c >= 0 && c < BOARD_SIZE && board[r][c] === EMPTY) {
                moves.push({ toRow: r, toCol: c, capturedPieces: [] });
                
                // 普通棋子只能移动一步
                if (!isKing) break;
                r += dr;
                c += dc;
            }
        }

        return moves;
    }


    // 递归查找连跳 (适用于所有棋子类型)
    // --- 修正：简化参数，不再需要 pieceType，因为 isKing 已经足够 ---
    // 根据规则，王棋在连跳时可以向任意方向移动，因此这里始终使用四个方向进行搜索。
    // --- 更新：王棋连跳后可停任意空格 ---
    function findFurtherJumps(fromRow, fromCol, capturedSoFar, isKing, isBlack) {
        // 所有棋子（包括王棋）连跳时都可以向四个方向搜索
        const directions = [[-1, -1], [-1, 1], [1, -1], [1, 1]];

        let furtherJumps = [];

        for (const [dr, dc] of directions) {
            let r = fromRow + dr;
            let c = fromCol + dc;
            
            // 沿着当前方向搜索
            while (r >= 0 && r < BOARD_SIZE && c >= 0 && c < BOARD_SIZE) {
                const targetPiece = board[r][c];
                
                if (targetPiece !== EMPTY) {
                    // 遇到自己的棋子或已经吃过的棋子，停止搜索这个方向
                    if ((isBlack && (targetPiece === BLACK_PIECE || targetPiece === BLACK_KING)) ||
                        (!isBlack && (targetPiece === WHITE_PIECE || targetPiece === WHITE_KING)) ||
                        capturedSoFar.some(p => p.row === r && p.col === c)) {
                        break;
                    } else {
                        // 遇到对方棋子，检查是否可以跳过
                        // --- 更新：王棋吃子后可停任意空格 ---
                        // 找到对方棋子后，沿着同一方向继续寻找空格
                        let jumpR = r + dr;
                        let jumpC = c + dc;
                        while (jumpR >= 0 && jumpR < BOARD_SIZE && jumpC >= 0 && jumpC < BOARD_SIZE && board[jumpR][jumpC] === EMPTY) {
                            const newCaptured = [...capturedSoFar, { row: r, col: c, type: targetPiece }]; // 记录被吃子的类型
                            const newPath = { toRow: jumpR, toCol: jumpC, capturedPieces: newCaptured };
                            
                            // 递归查找更远的跳跃
                            // --- 修正：调用 findFurtherJumps 时传入 isKing 状态 ---
                            const evenFurtherJumps = findFurtherJumps(jumpR, jumpC, newCaptured, isKing, isBlack);
                            
                            if (evenFurtherJumps.length > 0) {
                                // 如果有更远的跳跃，添加它们
                                furtherJumps.push(...evenFurtherJumps);
                            } else {
                                // 否则，这是一个终点
                                furtherJumps.push(newPath);
                            }
                            
                            // 王棋可以停在任意空格，所以继续寻找
                            if (isKing) {
                                jumpR += dr;
                                jumpC += dc;
                            } else {
                                // 普通棋子只能停在第一个空格
                                break;
                            }
                        }
                        break; // 在这个方向上找到一个跳跃（或检查完所有可能终点）后就停止搜索这个方向
                    }
                }

                // 继续沿直线搜索（对于王棋）
                if (isKing){
                    r += dr;
                    c += dc;                   
                } else {
                    // 普通棋子只能停在第一个空格
                    break;
                }

            }
        }

        // 返回当前层级找到的所有最长路径
        if (furtherJumps.length > 0) {
            const maxCaptures = Math.max(...furtherJumps.map(j => j.capturedPieces.length));
            return furtherJumps.filter(j => j.capturedPieces.length === maxCaptures);
        }

        return furtherJumps;
    }

    // 开始执行移动（可能是连续移动的第一步）
    function initiateMove(fromRow, fromCol, toRow, toCol, capturedPieces) {
        // 记录移动序列的起点
        if (currentMoveSequence.length === 0) {
            currentMoveSequence.push({ row: fromRow, col: fromCol });
        }
        // 执行单步移动
        executeSingleMove(fromRow, fromCol, toRow, toCol, capturedPieces);
    }

    // 执行单步移动并处理后续逻辑
    // --- 修复：修正了 piece = board[fromRow][col]; 中的 col 错误 ---
    function executeSingleMove(fromRow, fromCol, toRow, toCol, capturedPieces) {
        isProcessingMove = true;
        // --- 修复：使用正确的列索引 fromCol ---
        const piece = board[fromRow][fromCol]; 
        
        // 移动棋子
        board[toRow][toCol] = piece;
        board[fromRow][fromCol] = EMPTY;

        // 移除被吃的棋子
        let isKingPromoted = false;
        capturedPieces.forEach(cp => {
            board[cp.row][cp.col] = EMPTY;
        });


        // 清除高亮
        clearHighlights();




        // 修正：检查是否晋升为王棋 (仅在非连跳过程中检查)
        // 正确的晋升规则：
        // 黑棋（BLACK_PIECE）移动到第8行（索引7）晋升
        // 白棋（WHITE_PIECE）移动到第1行（索引0）晋升
        if (currentMoveSequence.length === 1 && 
            ((piece === BLACK_PIECE && toRow === BOARD_SIZE - 1) || // 黑棋到第8行
             (piece === WHITE_PIECE && toRow === 0))) {            // 白棋到第1行
            board[toRow][toCol] = (piece === BLACK_PIECE) ? BLACK_KING : WHITE_KING;
            isKingPromoted = true;
        }

        // 记录移动序列中的一步
        currentMoveSequence.push({ row: toRow, col: toCol, captured: [...capturedPieces], promoted: isKingPromoted });

        // 如果没有连跳，则完成整个移动序列
        finalizeMoveSequence();

        isProcessingMove = false;

        // 如果是人机模式，轮到AI移动
        if (gameMode === 'pvc' && currentPlayer === WHITE_PIECE && !isGameOver) {
            passBtn.style.display = 'block';
            setTimeout(makeAIMove, 500);
        } else {
            passBtn.style.display = 'none';
        }
    }

    // 完成整个移动序列（可能包含多次跳跃），并更新游戏状态
    function finalizeMoveSequence() {
        if (currentMoveSequence.length < 2) {
             console.error("Invalid move sequence length");
             return;
        }

        // 生成整个序列的行棋记录
        const moveNotation = generateMoveSequenceNotation(currentMoveSequence);
        moveHistory.push({
            sequence: [...currentMoveSequence],
            player: currentPlayer, // currentPlayer 在这里是指完成移动的那一方
            notation: moveNotation
        });
        addToHistory(moveNotation);

        // 重置移动序列
        currentMoveSequence = [];

        // 切换玩家
        currentPlayer = (currentPlayer === BLACK_PIECE || currentPlayer === BLACK_KING) ? WHITE_PIECE : BLACK_PIECE;
        selectedPiece = null;
        validMoves = [];
        undoBtn.disabled = false;

        renderBoard();
        updateStatus();

        // 检查游戏结束条件
        if (checkWin()) {
            isGameOver = true;
            // --- 修正获胜方显示逻辑 ---
            // 当 checkWin 返回 true 时，意味着 currentPlayer (下一个玩家) 无法移动。
            // 因此，刚刚完成移动的玩家 (即 moveHistory 中最后一步的 player) 是获胜方。
            const winner = moveHistory[moveHistory.length - 1].player;
            const winnerText = (winner === BLACK_PIECE || winner === BLACK_KING) ? '黑方' : '白方';
            statusElement.textContent = `${winnerText}获胜！`;
        }
    }

    // 生成整个移动序列的记谱法
    function generateMoveSequenceNotation(sequence) {
        if (sequence.length < 2) return "";

        const start = sequence[0];
        let notation = `${String.fromCharCode(97 + start.col)}${8 - start.row}`;

        for (let i = 1; i < sequence.length; i++) {
            const step = sequence[i];
            // 根据是否有被吃的子来决定分隔符
            const separator = step.captured && step.captured.length > 0 ? 'x' : '-';
            notation += `${separator}${String.fromCharCode(97 + step.col)}${8 - step.row}`;
            // 如果有升王，在最后添加升王标记
            if (step.promoted) notation += " (升王)";
        }
        return notation;
    }

    function addToHistory(notation) {
        const li = document.createElement('li');
        // 更规范的回合编号格式
        const moveNumber = Math.ceil(moveHistory.length );
        const isBlackMove = moveHistory.length % 2 === 1; // 黑方先行，所以奇数是黑方
        li.textContent = `${moveNumber}${isBlackMove ? '.' : '...'} ${notation}`;
        historyList.appendChild(li);
        historyList.scrollTop = historyList.scrollHeight; // 滚动到底部
    }

    // 修正悔棋逻辑，正确恢复被吃掉的棋子类型
    function undoMove() {
        if (moveHistory.length === 0 || isProcessingMove || currentMoveSequence.length > 0) return; // 不能在连跳过程中悔棋
        
        const lastMoveSet = moveHistory.pop();
        if (!lastMoveSet || !lastMoveSet.sequence) return;

        const sequence = lastMoveSet.sequence;
        const player = lastMoveSet.player;

        // 逆序还原整个移动序列
        // 1. 还原棋子位置和被吃的子
        for (let i = sequence.length - 1; i > 0; i--) {
            const to = sequence[i];
            const from = sequence[i - 1];
            
            // 移动棋子回去
            board[from.row][from.col] = board[to.row][to.col];
            board[to.row][to.col] = EMPTY;
            
            // 还原被吃的棋子 (使用记录的原始类型)
            if (to.captured) {
                 to.captured.forEach(cp => {
                     board[cp.row][cp.col] = cp.type; // <-- 修正：使用记录的类型 cp.type
                 });
            }
        }
        
        // 2. 如果第一步是升王，则还原为普通子
        const firstStep = sequence[0];
        const finalStep = sequence[sequence.length - 1];
        if (finalStep.promoted) {
             board[firstStep.row][firstStep.col] = (player === BLACK_PIECE) ? BLACK_PIECE : WHITE_PIECE;
        }

        // 切换回上一个玩家
        currentPlayer = player;
        
        // 清除最后一条历史记录的显示
        if (historyList.lastChild) {
            historyList.removeChild(historyList.lastChild);
        }

        selectedPiece = null;
        validMoves = [];
        clearHighlights();
        renderBoard();
        updateStatus();
        
        undoBtn.disabled = moveHistory.length === 0;
        
        if (gameMode === 'pvc' && currentPlayer === WHITE_PIECE) {
            passBtn.style.display = 'block';
            setTimeout(makeAIMove, 500);
        } else {
            passBtn.style.display = 'none';
        }
    }

    function checkWin() {
        let blackPieces = 0, whitePieces = 0;
        let blackHasMoves = false, whiteHasMoves = false;

        for (let row = 0; row < BOARD_SIZE; row++) {
            for (let col = 0; col < BOARD_SIZE; col++) {
                const piece = board[row][col];
                if (piece === BLACK_PIECE || piece === BLACK_KING) {
                    blackPieces++;
                    // --- 修正：调用 getValidMoves 时传入棋盘上的实际棋子类型 ---
                    if (!blackHasMoves && getValidMoves(row, col, piece).length > 0) {
                        blackHasMoves = true;
                    }
                } else if (piece === WHITE_PIECE || piece === WHITE_KING) {
                    whitePieces++;
                    // --- 修正：调用 getValidMoves 时传入棋盘上的实际棋子类型 ---
                    if (!whiteHasMoves && getValidMoves(row, col, piece).length > 0) {
                        whiteHasMoves = true;
                    }
                }
            }
        }

        // 1. 吃掉所有棋子
        if (blackPieces === 0) return true; // 白方胜
        if (whitePieces === 0) return true; // 黑方胜

        // 2. 无法移动
        if (currentPlayer === BLACK_PIECE || currentPlayer === BLACK_KING) {
            if (blackPieces > 0 && !blackHasMoves) return true; // 白方胜
        } else {
            if (whitePieces > 0 && !whiteHasMoves) return true; // 黑方胜
        }

        return false;
    }

    function updateStatus() {
        if (isGameOver) return;
        const playerText = (currentPlayer === BLACK_PIECE || currentPlayer === BLACK_KING) ? '黑方' : '白方';
        statusElement.textContent = `${playerText}行棋`;
    }

    // --- AI 逻辑 (简单实现) ---
    function makeAIMove() {
        if (isGameOver || currentPlayer !== WHITE_PIECE) return;
        
        isProcessingMove = true;
        statusElement.textContent = "白方 (AI) 思考中...";
        
        // 收集所有可能的移动
        let allPossibleMoves = [];
        for (let row = 0; row < BOARD_SIZE; row++) {
            for (let col = 0; col < BOARD_SIZE; col++) {
                const piece = board[row][col];
                if (piece === WHITE_PIECE || piece === WHITE_KING) {
                    // --- 修正：调用 getValidMoves 时传入棋盘上的实际棋子类型 ---
                    const moves = getValidMoves(row, col, piece);
                    moves.forEach(move => {
                        allPossibleMoves.push({
                            fromRow: row,
                            fromCol: col,
                            toRow: move.toRow,
                            toCol: move.toCol,
                            capturedPieces: move.capturedPieces,
                            // 使用独立的评估函数计算评分，传入移动前位置
                            score: evaluateMove(row, col, move, piece)
                        });
                    });
                }
            }
        }

        if (allPossibleMoves.length === 0) {
            // AI无法移动，游戏结束
            isGameOver = true;
            statusElement.textContent = "黑方获胜！(白方无子可动)";
            isProcessingMove = false;
            return;
        }

        // 选择评分最高的移动
        allPossibleMoves.sort((a, b) => b.score - a.score);
        const bestMove = allPossibleMoves[0];

        // 执行移动 (AI目前只执行一步，不处理复杂的连跳序列选择)
        setTimeout(() => {
             initiateMove(bestMove.fromRow, bestMove.fromCol, bestMove.toRow, bestMove.toCol, bestMove.capturedPieces);
             // 检查游戏是否结束（黑方是否已经没有棋子）
             if (checkWin()) {
                 // 游戏结束，不需要切换玩家
                 isGameOver = true;
                 // 确定获胜方，这里白方(AI)获胜
                 const winnerText = '白方';
                 statusElement.textContent = `${winnerText}获胜！`;
             } else {
                 // 游戏未结束，轮到黑方行棋
                 statusElement.textContent = "黑方行棋";
             }
             passBtn.style.display = 'none';
        }, 300); // 模拟思考时间
    }

    /**
     * 评估AI移动的评分函数
     * @param {number} fromRow - 移动前的行位置
     * @param {number} fromCol - 移动前的列位置
     * @param {Object} move - 移动对象，包含toRow, toCol, capturedPieces等属性
     * @param {number} piece - 棋子类型
     * @returns {number} 该移动的评分
     */
    function evaluateMove(fromRow, fromCol, move, piece) {
        let score = 0;
        
        // 基础评分：吃子数量（优先级最高）
        score += move.capturedPieces.length * 100;
        
        // 升王奖励：如果普通棋子能升王，给予额外奖励
        if (piece === WHITE_PIECE && move.toRow === 0) {
            score += 50;
        }
        
        // 吃子中包含王棋的奖励：吃掉对方王棋给予更高奖励
        move.capturedPieces.forEach(captured => {
            if (captured.type === BLACK_KING) {
                score += 75;
            }
        });
        
        // 位置优势：靠近对方底线的奖励
        score -= (BOARD_SIZE - 1 - move.toRow);
        
        // 模拟移动以评估后续安全性
        const originalPiece = board[move.toRow][move.toCol];
        const movingPiece = board[fromRow][fromCol];
        
        // 检查移动后是否升王
        let pieceAfterMove = movingPiece;
        if (movingPiece === WHITE_PIECE && move.toRow === 0) {
            pieceAfterMove = WHITE_KING;
        }
        
        board[fromRow][fromCol] = EMPTY;
        board[move.toRow][move.toCol] = pieceAfterMove;
        
        // 移除被吃掉的棋子
        let capturedPositions = [];
        move.capturedPieces.forEach(captured => {
            capturedPositions.push({
                row: captured.row, 
                col: captured.col, 
                piece: board[captured.row][captured.col]
            });
            board[captured.row][captured.col] = EMPTY;
        });
        
        // 检查移动后的位置是否容易被对方吃掉
        let isVulnerable = false;
        let vulnerableToKing = false;
        
        // 遍历对方所有棋子，看是否能吃掉刚移动的棋子
        for (let r = 0; r < BOARD_SIZE; r++) {
            for (let c = 0; c < BOARD_SIZE; c++) {
                const opponentPiece = board[r][c];
                if (opponentPiece === BLACK_PIECE || opponentPiece === BLACK_KING) {
                    // 获取对方棋子的可能移动
                    const opponentMoves = getValidMoves(r, c, opponentPiece);
                    for (const opponentMove of opponentMoves) {
                        // 检查是否有吃子且被吃子的位置是我们的新位置
                        if (opponentMove.capturedPieces.length > 0 && 
                            opponentMove.capturedPieces.some(captured => 
                                captured.row === move.toRow && captured.col === move.toCol)) {
                            isVulnerable = true;
                            if (opponentPiece === BLACK_KING) {
                                vulnerableToKing = true;
                            }
                            break;
                        }
                    }
                    if (isVulnerable) break;
                }
            }
            if (isVulnerable) break;
        }
        
        // 如果移动后会被吃掉，减少评分
        if (isVulnerable) {
            score -= 30; // 基础惩罚
            if (vulnerableToKing) {
                score -= 50; // 被王棋威胁的额外惩罚
            }
            // 如果是王棋或即将升王的棋子，惩罚更重
            if (pieceAfterMove === WHITE_KING) {
                score -= 40;
            }
        }
        
        // 额外评估：检查移动后是否会使其他己方棋子暴露
        for (let r = 0; r < BOARD_SIZE; r++) {
            for (let c = 0; c < BOARD_SIZE; c++) {
                const allyPiece = board[r][c];
                // 如果是己方棋子（除了当前移动的棋子）
                if ((allyPiece === WHITE_PIECE || allyPiece === WHITE_KING) &&
                    !(r === move.toRow && c === move.toCol)) {
                    let allyVulnerable = false;
                    // 检查这个棋子是否容易被吃掉
                    for (let or = 0; or < BOARD_SIZE; or++) {
                        for (let oc = 0; oc < BOARD_SIZE; oc++) {
                            const opponentPiece = board[or][oc];
                            if (opponentPiece === BLACK_PIECE || opponentPiece === BLACK_KING) {
                                const opponentMoves = getValidMoves(or, oc, opponentPiece);
                                for (const opponentMove of opponentMoves) {
                                    if (opponentMove.capturedPieces.length > 0 &&
                                        opponentMove.toRow === r &&
                                        opponentMove.toCol === c) {
                                        allyVulnerable = true;
                                        break;
                                    }
                                }
                                if (allyVulnerable) break;
                            }
                        }
                        if (allyVulnerable) break;
                    }
                    // 如果这个棋子变得容易被吃掉，给予一定的惩罚
                    if (allyVulnerable) {
                        score -= 15;
                    }
                }
            }
        }
        
        // 恢复被吃掉的棋子
        capturedPositions.forEach(pos => {
            board[pos.row][pos.col] = pos.piece;
        });
        
        // 恢复棋盘状态
        board[fromRow][fromCol] = movingPiece;
        board[move.toRow][move.toCol] = originalPiece;
        
        return score;
    }

    // --- 渲染 ---
    function renderBoard() {
        for (let row = 0; row < BOARD_SIZE; row++) {
            for (let col = 0; col < BOARD_SIZE; col++) {
                const square = document.querySelector(`.square[data-row="${row}"][data-col="${col}"]`);
                // 不再清空square，而是直接操作其子元素，避免移除事件监听器
                // square.innerHTML = ''; 

                // 移除旧的棋子元素
                const oldPiece = square.querySelector('.piece');
                if (oldPiece) {
                    square.removeChild(oldPiece);
                }

                const piece = board[row][col];
                if (piece !== EMPTY) {
                    const pieceElement = document.createElement('div');
                    pieceElement.classList.add('piece');
                    pieceElement.classList.add(piece === BLACK_PIECE || piece === BLACK_KING ? 'black' : 'white');
                    if (piece === BLACK_KING || piece === WHITE_KING) {
                        pieceElement.classList.add('king');
                    }
                    square.appendChild(pieceElement);
                }
            }
        }
    }

    // --- 启动游戏 ---
    window.onload = initGame;
</script>

</body>
</html>